import {
	HTTP_REQUEST_URL,
	HEADER
} from '@/config/app';

/**
 * 发送请求
 */

function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}) {
	let Url = HTTP_REQUEST_URL,
		header = HEADER;
	if (!noAuth) {
		//登录过期自动登录
		if (!uni.getStorageSync('token')) {
			// 登录 逻辑
			uni.navigateTo({
				url: '/pages/login/wxLogin'
			})
			return {
				code: 300,
				msg: '授权失效'
			}
		}
	}
	if (uni.getStorageSync('token')) header['user-token'] = uni.getStorageSync('token');
	return new Promise((reslove, reject) => {
		const locale = uni.getStorageSync('locale')
		uni.request({
			url: `${Url}/${url}?lang=${locale == 'zh' ? 'zh-cn': 'en-us'}`,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				if(res.data.code == 300) {
					reslove(res.data);
					uni.removeStorageSync('token')
					uni.removeStorageSync('userName')
					uni.removeStorageSync('englishname')
					uni.removeStorageSync('USERID')
					uni.navigateTo({
						url: '/pages/login/wxLogin'
					})
					return
				}
				
				if(res.data.code == 301) {
					reslove(res.data);
					uni.reLaunch({
						url: '/pages/indexBox/meetList'
					})
					return
				}
				
				if (noVerify) return reslove(res.data, res);
				
				if (res.data.code == 200) return reslove(res.data, res);
				
				uni.showModal({
					title: '提示',
					content: res.data.msg,
					showCancel: false,
					confirmText: '我知道了'
				});
				reject(res.data || '系统错误');

			},
			fail: (msg) => {
				let data = {
					mag: '请求失败',
					code: 1 //1没网
				}
				reject(data);
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});

export default request;